package th.retrofit.lib;

/**
 * https://leetcode-cn.com/problems/minimum-path-sum/
 * 给定一个包含非负整数的 m x n 网格 grid ，请找出一条从左上角到右下角的路径，使得路径上的数字总和为最小。
 *
 * 说明：每次只能向下或者向右移动一步。
 */
public class Solution64 {

    public int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 && j == 0) {
                    dp[i][j] = grid[i][j];
                } else if (i == 0) {
                    dp[i][j] = dp[i][j - 1] + grid[i][j];
                } else if (j == 0) {
                    dp[i][j] = dp[i - 1][j] + grid[i][j];
                } else {
                    dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
                }
            }
        }
        return dp[m - 1][n - 1];
    }

    public int minPathSum1(int[][] grid) {
        int[] minSum = new int[]{Integer.MAX_VALUE};
        int sum = 0;
        backtrack(0, 0, grid, minSum, sum);
        return minSum[0];
    }

    private void backtrack(int i, int j, int[][] grid, int[] minSum, int sum) {
        int m = grid.length;
        int n = grid[0].length;
        if (i == m || j == n) return;
        sum += grid[i][j];
        if (i == m - 1 && j == n - 1) {
            minSum[0] = Math.min(minSum[0], sum);
            return;
        }
        backtrack(i + 1, j, grid, minSum, sum);
        backtrack(i, j + 1, grid, minSum, sum);
    }

    public static void main(String[] args) {
        int[][] grid = new int[][]{{1,3,1}, {1,5,1},{4,2,1}};
        System.out.println(new Solution64().minPathSum1(grid));
    }

}
